import hashlib
import os
from datetime import datetime
import requests
from dotenv import load_dotenv
import shutil

def calculate_file_md5(file_path):
    """
    计算文件的 MD5 值
    :param file_path: 文件路径
    :return: MD5 字符串
    """
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()
def create_file_copy(src_file_path, dst_file_path=None):
    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")
    all_path=os.path.join(SOURCES_PATH,src_file_path)
    if not os.path.exists(all_path):
        raise FileNotFoundError(f"源文件不存在: {all_path}")
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    if dst_file_path is None:
        base, ext = os.path.splitext(src_file_path)
        print("base",base)
        print("ext",ext)
        dst_file_path = f"{base}{timestamp}(副本){ext}"
        dst_file_path1=os.path.join(SOURCES_PATH,dst_file_path)
        src_file_path=os.path.join(SOURCES_PATH,src_file_path)
    shutil.copy2(src_file_path, dst_file_path1)
    print(dst_file_path)
    return dst_file_path


def delete_file(file_path: str) -> bool:
    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")

    # 如果文件路径是相对路径，则拼接完整路径
    if not os.path.isabs(file_path):
        file_path = os.path.join(SOURCES_PATH, file_path)

    try:
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件不存在: {file_path}")

        os.remove(file_path)
        return True
    except Exception as e:
        print(f"删除文件失败: {str(e)}")
        return False

def download_file(file_url, save_path):

    # 获取保存目录
    save_dir = os.path.dirname(save_path)

    # 如果目录不存在，则创建
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    # 发起 HTTP 请求获取视频内容
    response = requests.get(file_url, stream=True)
    response.raise_for_status()  # 检查请求是否成功

    # 写入文件到本地
    with open(save_path, 'wb') as file:
        for chunk in response.iter_content(chunk_size=8192):
            file.write(chunk)

    print(f"文件已下载到: {save_path}")


if __name__ == '__main__':

    delete_file("D:\\aaaaazzz\\union_project\\union_project1\\a.mp3")